﻿using System;
using System.IO;
using System.Configuration;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Collections.Generic;
using System.Windows;
using System.Linq;

namespace PIBV
{
    public delegate void OnQuad(PDFQuadArgs e);

    public class AcrobatWrapper
    {

        public AcrobatWrapper()
        { 
        }

        public static void ConvertPdfToTiff(string srcPath,string destPath)
        {
            // Acrobat objects
            Acrobat.CAcroPDDoc pdfDoc;
            Acrobat.CAcroPDPage pdfPage;
            Acrobat.CAcroRect pdfRect;
            Acrobat.CAcroPoint pdfPoint;
            object js = null;

            string templatePortraitFile = Application.StartupPath + @"\pdftemplate_portrait.tif";
            string templateLandscapeFile = Application.StartupPath + @"\pdftemplate_portrait.tif"; ;

            // Get list of files to process from the input path
            // Could change to read list from database instead
            string[] files1 = Directory.GetFiles(srcPath, "*.pdf");
            //string[] files2 = Directory.GetFiles(srcPath, "*.PDF");

            //var files = files1.Concat(files2);

            //for (int n = 0; n < files.Length; n++)
            foreach(string file_name in files1)
            {
                try
                {
                    string inputFile = file_name.ToString();
                    string outputFile = destPath + file_name.Substring(file_name.LastIndexOf(@"\") + 1).Replace(".pdf", ".tif").Replace(".PDF", ".tif");

                    //string inputFile = files[n].ToString();
                    //string outputFile = pngOutputPath + files[n].Substring(files[n].LastIndexOf(@"\") + 1).Replace(".pdf", ".tif");

                    /* Could skip if thumbnail already exists in output path
                    FileInfo fi = new FileInfo(inputFile);
                    if (!fi.Exists) {} */

                    // Create the document (Can only create the AcroExch.PDDoc object using late-binding)
                    // Note using VisualBasic helper functions, have to add reference to DLL in
                    // C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\Microsoft.VisualBasic.dll
                    // Will always be available as .NET framework ships with all
                    pdfDoc = (Acrobat.CAcroPDDoc)Microsoft.VisualBasic.Interaction.CreateObject("AcroExch.PDDoc", "");
                        //(Acrobat.CAcroPDDoc)new Acrobat.AcroPDDocClass();
                    //(Acrobat.CAcroPDDoc)Microsoft.VisualBasic.Interaction.CreateObject("AcroExch.PDDoc", "");

                    bool ret = pdfDoc.Open(inputFile);

                    if (!ret)
                    {
                        throw new FileNotFoundException();
                    }

                    js = pdfDoc.GetJSObject();
                    js.GetType().InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod, null, js, new object[2] { outputFile, "com.adobe.acrobat.tiff" });

                    //// Get the number of pages (to be used later if you wanted to store that information)
                    //int pageCount = pdfDoc.GetNumPages();

                    //// Get the first page
                    //pdfPage = (Acrobat.CAcroPDPage)pdfDoc.AcquirePage(0);

                    //pdfPoint = (Acrobat.CAcroPoint)pdfPage.GetSize();

                    //pdfRect = (Acrobat.CAcroRect)Microsoft.VisualBasic.Interaction.CreateObject("AcroExch.Rect", "");

                    //pdfRect.Left = 0;
                    //pdfRect.right = pdfPoint.x;
                    //pdfRect.Top = 0;
                    //pdfRect.bottom = pdfPoint.y;

                    // Render to clipboard, scaled by 100 percent (ie. original size)
                    // Even though we want a smaller image, better for us to scale in .NET
                    // than Acrobat as it would greek out small text
                    // see http://www.adobe.com/support/techdocs/1dd72.htm
                    //pdfPage.CopyToClipboard(pdfRect, 0, 0, 100);

                    //IDataObject clipboardData = Clipboard.GetDataObject();

                    //if (clipboardData.GetDataPresent(DataFormats.Bitmap))
                    //{
                    //    Bitmap pdfBitmap = (Bitmap)clipboardData.GetData(DataFormats.Bitmap);

                    //    //pdfBitmap.Save(outputFile, System.Drawing.Imaging.ImageFormat.Bmp);
                    //    // Size of generated thumbnail in pixels
                    //    int thumbnailWidth = pdfPoint.x;
                    //    int thumbnailHeight = pdfPoint.y;

                    //    string templateFile;

                    //    // Switch between portrait and landscape
                    //    //if (pdfPoint.x < pdfPoint.y)
                    //    //{
                    //    templateFile = templatePortraitFile;
                    //    //}
                    //    //else
                    //    //{
                    //    //	templateFile = templateLandscapeFile;
                    //    //	// Swap width and height (little trick not using third temp variable)
                    //    //		thumbnailWidth = thumbnailWidth ^ thumbnailHeight;
                    //    //		thumbnailHeight = thumbnailWidth ^ thumbnailHeight;
                    //    //		thumbnailWidth = thumbnailWidth ^ thumbnailHeight;
                    //    //	}

                    //    // Load the template graphic
                    //    Bitmap templateBitmap = new Bitmap(templateFile);

                    //    // Render to small image using the bitmap class

                    //    Image pdfImage = pdfBitmap.GetThumbnailImage(thumbnailWidth, thumbnailHeight,
                    //                                                 null, IntPtr.Zero);

                    //    // Create new blank bitmap (+ 7 for template border)						 
                    //    //Bitmap thumbnailBitmap = new Bitmap(thumbnailWidth , thumbnailHeight ,
                    //    //									System.Drawing.Imaging.PixelFormat.Format64bppArgb);

                    //    // To overlayout the template with the image, we need to set the transparency
                    //    // http://www.sellsbrothers.com/writing/default.aspx?content=dotnetimagerecoloring.htm
                    //    //templateBitmap.MakeTransparent();

                    //    //using (Graphics thumbnailGraphics = Graphics.FromImage(thumbnailBitmap))
                    //    //{
                    //    //// Draw rendered pdf image to new blank bitmap
                    //    //    thumbnailGraphics.DrawImage(pdfImage, 0, 0, thumbnailWidth, thumbnailHeight);

                    //    //// Draw template outline over the bitmap (pdf with show through the transparent area)
                    //    //   thumbnailGraphics.DrawImage(templateBitmap, 0, 0);



                    //    // Save as .png file
                    //    //     thumbnailBitmap.Save(outputFile, System.Drawing.Imaging.ImageFormat.Tiff);

                    //    //     Console.WriteLine("Generated thumbnail... {0}", outputFile);
                    //    // }

                        pdfDoc.Close();

                        // Not sure how why it is to do this, but Acrobat is not the best behaved COM object
                        // see http://blogs.msdn.com/yvesdolc/archive/2004/04/17/115379.aspx
                        //Marshal.ReleaseComObject(pdfPage);
                        //Marshal.ReleaseComObject(pdfRect);
                        Marshal.ReleaseComObject(pdfDoc);
                    //}

                }
                catch (System.Exception ex)
                {
                    Debug.WriteLine(ex.ToString());
                }
            }
        }

        public static void FindText(string textToFind, string folder, string fileName,OnQuad onQuad)
        {
            // Acrobat objects
            Acrobat.CAcroPDDoc pdfDoc = null;
            Acrobat.CAcroPDPage pdfPage = null;
            Acrobat.CAcroPoint pdfPoint = null;
            object js = null;

            try
            {
                string inputFile = folder + fileName;

                // Create the document (Can only create the AcroExch.PDDoc object using late-binding)
                // Note using VisualBasic helper functions, have to add reference to DLL in
                // C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\Microsoft.VisualBasic.dll
                // Will always be available as .NET framework ships with all
                pdfDoc = (Acrobat.CAcroPDDoc)Microsoft.VisualBasic.Interaction.CreateObject("AcroExch.PDDoc", "");

                bool ret = pdfDoc.Open(inputFile);

                if (!ret)
                {
                    throw new FileNotFoundException();
                }

                // Get the number of pages (to be used later if you wanted to store that information)
                int pageCount = pdfDoc.GetNumPages();
                // Get the first page
                pdfPage = (Acrobat.CAcroPDPage)pdfDoc.AcquirePage(0);
                pdfPoint = (Acrobat.CAcroPoint)pdfPage.GetSize();

                js = pdfDoc.GetJSObject();

                #region Find Text

                int wordsCount = Convert.ToInt32(js.GetType().InvokeMember("getPageNumWords", System.Reflection.BindingFlags.InvokeMethod, null, js, new object[1] { 0 })); ;
                List<string> words = new List<string>();

                for (int i = 0; i < wordsCount; i++)
                {
                    string word = js.GetType().InvokeMember("getPageNthWord", System.Reflection.BindingFlags.InvokeMethod, null, js, new object[2] { 0, i }) as string;
                    Debug.WriteLine(word);
                    words.Add(word);
                }

                //int wordPosition = words.FindIndex(s => { return s.ToUpperInvariant() == textToFind.ToUpperInvariant(); });
                //List<string> words2 = words.FindAll(s => { return s.ToUpperInvariant() == textToFind.ToUpperInvariant(); });

                for (int i = 0; i < words.Count; i++)
                {
                    if (words[i] == textToFind || String.IsNullOrEmpty(textToFind) )
                    {
                        object[] quad = (object[])js.GetType().InvokeMember("getPageNthWordQuads", System.Reflection.BindingFlags.InvokeMethod, null, js, new object[2] { 0, i });
                        object[] arr = (object[])quad[0];

                        if (onQuad != null)
                        {
                            PDFQuadArgs args = new PDFQuadArgs(
                                new Point(pdfPoint.x, pdfPoint.y),
                                new Point(Convert.ToInt32(arr[0]), Convert.ToInt32(arr[1])),
                                new Point(Convert.ToInt32(arr[2]), Convert.ToInt32(arr[3])),
                                new Point(Convert.ToInt32(arr[4]), Convert.ToInt32(arr[5])),
                                new Point(Convert.ToInt32(arr[6]), Convert.ToInt32(arr[7])),
                                words[i]
                                );
                            onQuad(args);
                        }
                    }
                }

                #endregion

                pdfDoc.Close();

                // Not sure how why it is to do this, but Acrobat is not the best behaved COM object
                // see http://blogs.msdn.com/yvesdolc/archive/2004/04/17/115379.aspx
                Marshal.ReleaseComObject(pdfPage);
                //Marshal.ReleaseComObject(pdfRect);
                Marshal.ReleaseComObject(pdfDoc);
                Marshal.ReleaseComObject(pdfPoint);
            }
            catch (System.Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }

        }

    }

}